<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/12/11
 */

namespace basic;
use app\common\model as M;

use app\wap\model\user\User;
use app\wap\model\user\WechatUser;
use behavior\wap\WapBehavior;
use service\JsonService;
use think\Controller;
use behavior\wechat\UserBehavior;
use service\HookService;
use service\UtilService;
use service\WechatService;
use think\Cookie;
use think\Request;
use think\Session;
use think\Url;
use think\Cache;

class WapBasic extends Controller
{
    protected $uid        = 0;
    protected $userInfo   = [];
    protected $spread_uid = 0;
    protected $isWechat   = false;
    protected $org_id     = 0;
    protected $school_id  = 0;

    protected function _initialize()
    {

        parent::_initialize();

        // org_id可能为纯数字，也可能是加密后的字符串
        $org_id    = $this->request->param('org_id');
        $school_id = $this->request->param('school_id');
        if ( $org_id ) {
            \think\Log::record('CACHED ORG ID FROM PARAM ' . $org_id , $org_id);
            \app\wap\model\organ\Organ::setCacheOrganId($org_id);
        } else {
            $org_id = \app\wap\model\organ\Organ::getCachedOrganId();
        }

        \think\Log::record('CACHED ORG ID IS ' . $org_id , $org_id);

        $this->userInfo = M\User::get_login();
        if ( !empty($this->userInfo) ) {
            $this->uid   = $this->userInfo['uid'];
        }

        $this->spread_uid = $this->request->param('spread_uid');
        $this->isWechat   = UtilService::isWechatBrowser();
        $this->org_id     = $org_id;
        $this->school_id  = $school_id;

        $this->assign('userInfo',$this->userInfo);
        $this->assign('uid',$this->uid);
        $this->assign('spread_uid',$this->spread_uid);
        $this->assign('isWechat',$this->isWechat);
        $this->assign('login_url', Url::build('login/index') . '?ref=' .base64_encode(htmlspecialchars($this->request->url(true))) );

        HookService::listen('wap_init',null,null,false,WapBehavior::class);
    }

    /**
     * 操作失败 弹窗提示
     * @param string $msg
     * @param int $url
     * @param string $title
     */
    protected function failed($msg = '操作失败', $url = 0, $title='信息提示')
    {

        if($this->request->isAjax()){
            exit(JsonService::fail($msg,$url)->getContent());
        }else {
            $this->assign(compact('title', 'msg', 'url'));
            exit($this->fetch('public/error'));
        }
    }

    /**
     * 操作成功 弹窗提示
     * @param $msg
     * @param int $url
     */
    protected function successful($msg = '操作成功', $url = 0, $title='成功提醒')
    {
        if($this->request->isAjax()){
            exit(JsonService::successful($msg,$url)->getContent());
        }else {
            $this->assign(compact('title', 'msg', 'url'));
            exit($this->fetch('public/success'));
        }
    }

    public function _empty($name)
    {
        $url = strtolower($name) == 'index' ? Url::build('Index/index','',true,true) : 0;
        return $this->failed('请求页面不存在!',$url);
    }

    /**
     * 微信用户自动登陆
     * @return string $openid
     */
    protected function oauth()
    {
        if ( !empty($this->userInfo) ) return $this->userInfo;

        if( !$this->isWechat ) exit($this->failed('请在微信客户端打开链接'));
        if($this->request->isAjax()) exit($this->failed('请登陆!'));

        try {
            $wechatInfo = (new GetWxUser)->get_user_all();
        } catch ( \Exception $e ) {
            \think\Log::record(json_encode($e));
        }

        \think\Log::record('WECHAT AUTH' , $this->request->url(true));
        $wechatInfo['spread_uid'] = $this->spread_uid;
        return M\User::wechat_login($wechatInfo , $this->org_id , $this->school_id);

        // $openid = Session::get('loginOpenid','wap');
        // if($openid) return $openid;
        // if(!UtilService::isWechatBrowser()) exit($this->failed('请在微信客户端打开链接'));
        // if($this->request->isAjax()) exit($this->failed('请登陆!'));
        // $errorNum = (int)Cookie::get('_oen');
        // if($errorNum && $errorNum > 3) exit($this->failed('微信用户信息获取失败!!'));
        // try{
        //     $wechatInfo = WechatService::oauthService()->user()->getOriginal();
        // }catch (\Exception $e){
        // 	file_put_contents('oen.txt', json_encode([
        // 		'msg'=>$e->getMessage(),
        // 		'file'=>$e->getFile()
        // 	]));
        //     Cookie::set('_oen',++$errorNum,900);
        //     exit(WechatService::oauthService()->scopes(['snsapi_base'])
        //         ->redirect($this->request->url(true))->send());
        // }
        // if(!isset($wechatInfo['nickname'])){
        //     $wechatInfo = WechatService::getUserInfo($wechatInfo['openid']);
        //     if(!$wechatInfo['subscribe'] && !isset($wechatInfo['nickname']))
        //         exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
        //             ->redirect($this->request->url(true))->send());
        //     if(isset($wechatInfo['tagid_list']))
        //         $wechatInfo['tagid_list'] = implode(',',$wechatInfo['tagid_list']);
        // }else{
        //     if(isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
        //     $wechatInfo['subscribe'] = 0;
        // }
        // Cookie::delete('_oen');
        // $openid = $wechatInfo['openid'];
        // $wechatInfo['spread_uid']=$spread_uid;
        // UserBehavior::wechatOauthAfter($openid,$wechatInfo);
        // //HookService::afterListen('wechat_oauth',$openid,$wechatInfo,false,UserBehavior::class);
        // Session::set('loginOpenid',$openid,'wap');
        // Cookie::set('is_login',1);
        // return $openid;
    }
}


/**
 * 获取微信用户信息
 * @author: Lucky hypo
 */
class GetWxUser extends WapBasic {
    private $appid = 'wx1a2b2e79547a8121';
    private $appsecret = '866797146e43cf3cf38ce72008f7b9d6';


    protected function _initialize()
    {
        parent::_initialize();

        $config    = M\OrganConfig::get_config_values($this->org_id , ['wechat_appid' , 'wechat_appsecret']);

        if ( isset($config['wechat_appid']) && $config['wechat_appid'] != '' ) {
            $this->appid = $config['wechat_appid'];
        }

        if ( isset($config['wechat_appsecret']) && $config['wechat_appsecret'] != '' ) {
            $this->appsecret = $config['wechat_appsecret'];
        }
    }
   /**
    * 1、获取微信用户信息，判断有没有code，有使用code换取access_token，没有去获取code。
    * @return array 微信用户信息数组
    */
    public function get_user_all(){
        if (!isset($_GET['code'])){//没有code，去微信接口获取code码
            $callback = $this->request->url(true);//微信服务器回调url，这里是本页url

            if ( strpos($callback , '?') ) {
                $callback .= '&org_id=' . $this->org_id . '&school_id=' . $this->school_id;
            } else {
                $callback .= '?org_id=' . $this->org_id . '&school_id=' . $this->school_id;
            }

            $this->get_code($callback);
        } else {//获取code后跳转回来到这里了
            $code = $_GET['code'];
            $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
            $data_all = $this->get_user_info($data['access_token'],$data['openid']);//获取微信用户信息
            return $data_all;
        }
    }

   /**
    * 2、用户授权并获取code
    * @param string $callback 微信服务器回调链接url
    */
    private function get_code($callback){
        $appid = $this->appid;
        $scope = 'snsapi_userinfo';
        $state = md5(uniqid(rand(), TRUE));//唯一ID标识符绝对不会重复
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) .  '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        header("Location:$url");
    }
   /**
    * 3、使用code换取access_token
    * @param string 用于换取access_token的code，微信提供
    * @return array access_token和用户openid数组
    */
    private function get_access_token($code){
        $appid = $this->appid;
        $appsecret = $this->appsecret;
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }
  /**
    * 4、使用access_token获取用户信息
    * @param string access_token
    * @param string 用户的openid
    * @return array 用户信息数组
    */
    private function get_user_info($access_token,$openid){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }
}